package pl.edu.agh.uhm.core;

import java.util.Dictionary;
import java.util.List;

import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.service.upnp.UPnPDevice;

import pl.edu.agh.uhm.discoverer.DiscovererListener;
import pl.edu.agh.uhm.discoverer.Hypervisor;
import pl.edu.agh.uhm.discoverer.HypervisorsDiscoverer;

public class HypervisorsManager implements ServiceListener,DiscovererListener{
	
	
	ServiceReference sr;
	DevicesTreeView view;
	
	
	
	public HypervisorsManager(DevicesTreeView view){
		
		this.view=view;
		
	}
	
	public void init(){
		
		Activator.context.registerService( DiscovererListener.class.getName(),this, null);
		try{
			Activator.context.addServiceListener(this,
				"(&"+
				"("+Constants.OBJECTCLASS+"="+HypervisorsDiscoverer.class.getName()+"))"
				);
			System.out.println("listener of discoverer activated");
			ServiceReference[] roots = null; 
		
			sr = Activator.context.getServiceReference(HypervisorsDiscoverer.class.getName());
			
		}catch (InvalidSyntaxException e) {
				e.printStackTrace();
		}
		
	}
	
	public void getAllVMs(){
		
		if(sr!=null){
			HypervisorsDiscoverer hd=(HypervisorsDiscoverer)Activator.context.getService(sr);
			List<Hypervisor> hypervisors=hd.getHypervisors();
			if(hypervisors!=null){
				System.out.println(hypervisors.size()+" hypervisors found");
				for(Hypervisor h:hypervisors)
					System.out.println(h);
			}
			else
				System.out.println("No hypervisors found");
			
		}
		
	}

	@Override
	public void serviceChanged(ServiceEvent event) {
		
	
		switch(event.getType()){
			case ServiceEvent.REGISTERED:{
				System.out.println("Hypervisors discoverer service registered");
				sr=event.getServiceReference();
				getAllVMs();
				break;
			}
			case ServiceEvent.MODIFIED:{
				System.out.println("Hypervisors discoverer service modified");
				break;
			}
			case ServiceEvent.UNREGISTERING:{	
				System.out.println("Hypervisors discoverer service unregistered");
				
				break;		
			}
		}	
	}

	@Override
	public void hypervisorDeleted(Hypervisor hypervisor) {
		System.out.println("WOW Received info about deleted hypervisor");
		view.addHypervisor();
		
	}

	@Override
	public void hypervisorDiscovered(Hypervisor hypervisor) {
		System.out.println("WOW Received info about new hypervisor discovered");
		view.addHypervisor();
		
	}

	@Override
	public void hypervisorModified(Hypervisor hypervisor) {
		System.out.println("Received info about modified hypervisor");	
	}
	
	
	
	

}
